<template>
  <div class="el-main">
    <button :disabled="show" @click="getCode">倒计时</button>
    <button>{{ times }}s</button>
    <br>
    <input style="margin-top: 20px" v-model="msg"></input><br>

    <span style="color: red;">{{ hour }}:{{ minute }}:{{ second }}</span>
  </div>
</template>

<script>
export default {
  name: "PassValidation",
  data() {
    return {
      hour: 0,
      minute: 0,
      second: 0,
      times: 10,
      msg: "",
      show: false
    }
  },
  props: {
    remainTime: {    // 倒计时间总秒数
      default: '10'
    }
  },
  watch: {
    msg: {
      handler(itemNew, itemOld) {
        if (itemNew == "123") {
          alert("错误");
        }
      }
    }
  },
  methods: {
    getCode() {
      this.show = true;
      this.timer = setInterval(() => {
        this.times--
        if (this.times === 0) {
          this.show = false;
          this.$message.info("考试结束");
          clearInterval(this.timer);
          this.times = 10;
        }
      }, 1000)
    },

    countDowm () {
      let self = this;
      clearInterval(this.promiseTimer)
      this.promiseTimer = setInterval(function () {
        if (self.hour==0&&self.minute==0&&self.second==0){
          //alert('结束')
        }
        if (self.hour === 0) {
          if (self.minute !== 0 && self.second === 0) {
            self.second = 59
            self.minute -= 1
          } else if (self.minute === 0 && self.second === 0) {
            self.second = 0
            self.$emit('countDowmEnd', true)
            clearInterval(self.promiseTimer)
          } else {
            self.second -= 1
          }
        } else {
          if (self.minute !== 0 && self.second === 0) {
            self.second = 59
            self.minute -= 1
          } else if (self.minute === 0 && self.second === 0) {
            self.hour -= 1
            self.minute = 59
            self.second = 59
          } else {
            self.second -= 1
          }
        }
      }, 1000);

    },
    formatNum (num) {
      return num < 10 ? '0' + num : '' + num
    }
  },
  mounted() {
    //this.validation();
    if (this.remainTime > 0) {
      this.hour = Math.floor((this.remainTime / 3600) % 24)
      this.minute = Math.floor((this.remainTime / 60) % 60)
      this.second = Math.floor(this.remainTime % 60)
      this.countDowm()
    }

  }
}
</script>

<style lang="scss" scoped>
.el-main {
  border-radius: 30px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>
